from rest_framework import serializers
from django_redis import get_redis_connection

# 因为没有设置模型所以使用serializers.Serializer

class RegisterSmsCodeSerializer(serializers.Serializer):

    text = serializers.CharField(label='图片验证码',max_length=4,min_length=4,required=True)
    image_code_id = serializers.UUIDField(label='uuid',required=True)


    #对多个字段进行校验
    def validate(self, attrs):

        image_code_id = attrs.get('image_code_id')
        #1.获取用户提交的图片码
        text = attrs.get('text')
        #2.获取redis的图片验证码
        #2.1连接redis
        redis_conn = get_redis_connection('code')
        #2.2获取
        redis_text = redis_conn.get('img_%s'%image_code_id)
        #2.3注意有效期
        if redis_text is None:
            raise serializers.ValidationError('图片验证码已过期')

        #3.对比
        #注意reids是二进制
        if redis_text.decode().lower() != text.lower():
            raise serializers.ValidationError('图片验证码不一致')





        #必须将验证的值返回
        return attrs
